import { Admin, Building, Floor, Project, SearchRet } from '../../../shared/model/defination';
import { Component, OnInit } from '@angular/core';
import { Helper } from '../../common/index';
import { ControlBase } from '../../../shared/dynamicform/controlbase';
import { TextBox } from '../../../shared/dynamicform/textbox-control';
import { SelectBox } from '../../../shared/dynamicform/selectbox-control';
import { EmailValidator, NumberValidator } from '../../../shared/dynamicform/my-validator';
import { FormGroup, Validators } from '@angular/forms';
import { Observable } from 'rxjs/Rx';
import { Router, ActivatedRoute, Params, Route } from '@angular/router';
import { FloorService } from '../../../services/floor-service';
import { FloorRequest } from '../../../dtos/floorRequest';
// import { Floor, Location, Project, Building } from '../../../entities/entities';
import { MdlSnackbarService } from '@angular-mdl/core';
import { LocationService } from '../../../services/location-service';
import { ProjectService } from '../../../services/project-service';
import { BuildingService } from '../../../services/building-service';
import { UserService } from '../../../services/user-service';
import { SessionUser, SessionService } from '../../../services/session-service';
import * as _ from 'lodash';


@Component({
	selector: 'floor-edit',
	templateUrl: './edit.component.html',
	styleUrls: ['./edit.component.scss'],
	providers: [FloorService, LocationService, ProjectService, BuildingService, SessionService, UserService]
})
export class EditComponent implements OnInit {

	public get IsEdit() {
		return this._route.snapshot.params['id'] !== undefined;
	}

	public userRole: string;

	private _editItem: Floor;

	public isFormPosting: boolean = false;

	public locationConfigs: any;

	public isPosting: boolean = false;

	public projectConfigs: Array<any>;

	public selectedProject: number = -1;

	public selectedBuilding: number;

	formInputs: ControlBase<any>[];

	formControls: any;

	constructor(
		private _route: ActivatedRoute,
		private _router: Router,
		private _locationService: LocationService,
		private _floorService: FloorService,
		private _mdlSnackbarService: MdlSnackbarService,
		private _projectService: ProjectService,
		private _buildingService: BuildingService,
		private _sessionService: SessionService,
		private _userService: UserService
	) { }

	async ngOnInit() {
		try {
			this.isPosting = true;
			let floorId = this.IsEdit ? +this._route.snapshot.params['id'] : 0;
			if (floorId) {
				this._editItem = await this._floorService.Get(floorId).toPromise();
				this.selectedProject = this._editItem.building.project.id;
				this.selectedBuilding = this._editItem.building.id;
			}

			let projects$ = <Observable<Project[]>>this._projectService.All();
			let projects = await projects$.toPromise();
			this.projectConfigs = projects.map(p => {
				return {
					key: p.name,
					value: p.id
				}
			});
			let buildings$ = <Observable<SearchRet<Building>>>this._buildingService.getAllBuildings();
			let buildings: any = await buildings$.toPromise();
			this.locationConfigs = _.chain(buildings.items)
				.map(b => {
					return { key: b.buildingNumber, value: b.id, projectId: b.project.id };
				})
				.groupBy(r => r.projectId)
				.value();

			this.userRole = this._sessionService.getRoles()[0];
			if (this.userRole === '物业') {
				let session: Admin = await this._sessionService.getCurrentUser();
				let sessionUser = await this._userService.Get(session.id).toPromise();
				this.selectedProject = sessionUser.company.locations[0].project.id;
			}
			this.formControls = this._setForm(this._editItem);
			this.isPosting = false;
		}
		catch (e) {
			if (e.status === 401) {
				this._router.navigate(['/login']);
			}
		}
		finally {

		}
	}

	private _setForm(data: any): any {

		this.formInputs = [
			new TextBox({
				type: 'text',
				key: 'index',
				label: '楼层号(单位：层，只填写数字)',
				value: data ? data.index : '',
				required: true,
				order: 0,
				groupId: 0,
				validators: [Validators.required, NumberValidator()]
			}),
			// new TextBox({
			// 	type: 'text',
			// 	key: 'name',
			// 	label: '楼层名',
			// 	value: data ? data.name : '',
			// 	required: true,
			// 	order: 1,
			// 	groupId: 1,
			// 	require: true,
			// 	validators: Validators.required
			// }),
			new SelectBox({
				key: 'projectId',
				label: '所属项目',
				options: this.projectConfigs,
				value: this.selectedProject,
				order: 4,
				disabled: this.userRole === '物业',
				groupId: 4,
				require: true,
				validators: Validators.required
			})
			,
			new SelectBox({
				key: 'buildingId',
				label: '所属大楼',
				options: this.locationConfigs[this.selectedProject],
				value: this.selectedBuilding,
				order: 5,
				groupId: 4,
				require: true,
				validators: Validators.required
			})
		];
		return Helper.setGroupForm(this.formInputs);
	}
	async save(df: any) {
		this.isFormPosting = true;
		let form = <FormGroup>df.form;
		if (!form.valid) {
			return false;
		}
		let request: FloorRequest = {
			index: form.value.index,
			name: form.value.name,
			buildingId: form.value.buildingId
		};
		let action;
		if (!this.IsEdit) {
			action = this._floorService.Create(request).toPromise();
		}
		else {
			request.id = this._editItem.id;
			action = this._floorService.Update(request).toPromise();
		}
		try {
			let resp = await action;
			if (resp) {
				this._mdlSnackbarService.showToast('保存成功！', 2000);
				this._router.navigate(['/floor']);
			}
		}
		catch (e) {
			this._mdlSnackbarService.showToast('操作失败，请稍后重试！', 2000);
		}
		finally {
			this.isFormPosting = false;
		}
	}
	public onLoadFormData(form) {
		let projectId = form.projectId;
		let building: SelectBox = <SelectBox>this.formInputs.find(f => f.key === 'buildingId')
		building.options = this.locationConfigs[projectId];
	}
}
